package cn.jingzhuan.fm.di.module

import cn.jingzhuan.fm.BuildConfig
import cn.jingzhuan.fm.network.FMApiService
import com.google.gson.FieldNamingPolicy
import com.google.gson.Gson
import com.google.gson.GsonBuilder
import dagger.Provides
import okhttp3.HttpUrl
import okhttp3.OkHttpClient
import retrofit2.Retrofit
import retrofit2.adapter.rxjava2.RxJava2CallAdapterFactory
import retrofit2.converter.gson.GsonConverterFactory
import java.util.concurrent.TimeUnit

@dagger.Module
class FMNetworkModule {

    @Provides internal  fun provideFMApiService(retrofit: Retrofit):FMApiService {
        return retrofit.create(FMApiService::class.java)
    }

    @Provides internal fun provideRetrofit(client: OkHttpClient,gson: Gson,baseUrl:HttpUrl): Retrofit {
        return Retrofit.Builder().client(client)
                .baseUrl(baseUrl)
                .addConverterFactory(GsonConverterFactory.create(gson))
                .addCallAdapterFactory(RxJava2CallAdapterFactory.createAsync())
                .build()
    }

    @Provides internal fun provideOkHttp(): OkHttpClient {
        val builder = OkHttpClient.Builder()
                .readTimeout(15, TimeUnit.SECONDS)
                .writeTimeout(15, TimeUnit.SECONDS)

        return builder.build()
    }


    @Provides internal fun provideBaseUrl(): HttpUrl {
        return HttpUrl.parse(BuildConfig.FM_HOST)!!
    }

    @Provides fun provideGson(): Gson {
        return GsonBuilder()
                .setFieldNamingPolicy(FieldNamingPolicy.LOWER_CASE_WITH_UNDERSCORES)
                .create()
    }

}